package cn.hfatec.shms.web.ss.ssCustomer.action;


import cn.hfatec.shms.web.ss.ssCriteria.service.SsCriteriaService;
import cn.hfatec.shms.web.ss.ssCriteriaSecond.service.SsCriteriaSecondService;
import cn.hfatec.shms.web.ss.ssCrux.model.SsCrux;
import cn.hfatec.shms.web.ss.ssCrux.service.SsCruxService;
import cn.hfatec.shms.web.ss.ssHd.model.SsHd;
import cn.hfatec.shms.web.ss.ssHd.service.SsHdService;
import cn.hfatec.shms.web.yk.ykBmb.model.YkBmbParams;
import cn.hfatec.shms.web.yk.ykHsb.model.YkHsb;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;


import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.web.ss.ssCustomer.model.SsCustomerParams;
import cn.hfatec.shms.web.ss.ssCustomer.model.SsCustomer;
import cn.hfatec.shms.web.ss.ssCustomer.service.SsCustomerService;
import cn.hfatec.shms.base.ShmsBaseAction;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;



/**
 *
 * @author hfatec codegen
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Controller
@RequestMapping("/ss/ssCustomer")
public class SsCustomerAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "SsCustomerService")
    private SsCustomerService ssCustomerService;
    //服务层
    @Resource(name = "SsCruxService")
    private SsCruxService ssCruxService;
    //服务层
    @Resource(name = "SsHdService")
    private SsHdService ssHdService;

    /**
     *
     * 查询列表
     *
     */
    @RequestMapping("/list")
    public String list(SsCustomerParams ssCustomerParams, Page page, Model model) {

        Table table = ssCustomerService.querySsCustomerTable(ssCustomerParams, page);
        model.addAttribute("ssCustomersTable", table);
        model.addAttribute("ssCustomerParams", ssCustomerParams);
        return "/ss/ssCustomer/list";
    }

    /**
     *
     * 异步查询列表
     *
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(SsCustomerParams ssCustomerParams, Page page, Model model) {
        try {
            list(ssCustomerParams, page, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/ss/ssCustomer/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     *
     * 跳转到新增页
     *
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(Model model) {
        try {
            SsCustomer ssCustomer = new SsCustomer();
            model.addAttribute("ssCustomer", ssCustomer);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/ss/ssCustomer/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }


    /**
     *
     * 跳转到编辑页
     *
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) throws ParseException {

        try {
            SsCustomer ssCustomer = ssCustomerService.getSsCustomer(id);
            model.addAttribute("ssCustomer", ssCustomer);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/ss/ssCustomer/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goCheck")
    @ResponseBody
    public String goCheck(String testDate, String testEnd) {
        try {
            /*List<SsHd> SsHd= ssHdService.getSsHdNum();
            if(SsHd != null && !SsHd.isEmpty() ){
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "请先在《核对信息》模块核对干预和财务的客户姓名和电话").toString();
            }*/
            if (testDate.length() == 0) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "更新开始时间不能为空").toString();
            }
            if (testEnd.length() == 0) {
                testEnd = testDate;
            }
            long a = dataZ(testDate, testEnd) + 1;
      /*      if (a < 0 || a > 15) {
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "更新时间范围大于15或者小于0").toString();
            }*/
            updateCrux(testDate, testEnd);

            ssCustomerService.updateSsCustomer(testDate,testEnd);
            SsCustomer customer=new SsCustomer();


            if (customer != null) {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", customer).toString();
            } else {
                return new JsonResponse(JsonResponse.RETURN_SUCCESS, "", new SsCustomer()).toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     *
     * 更新客户指标
     *
     */
    private void updateCrux(String testDate, String testEnd){

        List<SsCrux> crux = ssCruxService.selectCrux(testDate, testEnd);
        if (crux != null && !crux.isEmpty()) {
            for (SsCrux ssCrux : crux) {
                SsCrux cruxs = ssCruxService.getSsCruxCruxId(ssCrux.getCruxId());
                if (cruxs != null) {
                    ssCrux.setId(cruxs.getId());
                }
                ssCruxService.saveSsCrux(ssCrux);

            }

        }
    }
    private long dataZ(String testDate, String testEnd) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date hsDate = formatter.parse(testDate);
        Date EndDate = formatter.parse(testEnd);
        long day = (EndDate.getTime() - hsDate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }
    /**
     *
     * 根据IDs删除数据
     *
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteSsCustomer(String ids) {
        try {
            List<String> idList = new ArrayList<String>();
            if(ids.length() > 0) {
                idList = Arrays.asList(ids.split(","));
            }
            ssCustomerService.deleteSsCustomerBatch(idList);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据" + ids + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     *
     * 保存数据
     *
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveSsCustomer(@Valid SsCustomer ssCustomer, BindingResult result) {

        try {
            if(result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            ssCustomerService.saveSsCustomer(ssCustomer);
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("数据SsCustomer保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE).toString();
    }
    /**
     * 导出excel
     */
    @RequestMapping("/export")
    @ResponseBody
    public String export(SsCustomerParams ssCustomerParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            ssCustomerService.exportExcel(ssCustomerParams, request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }
}
